package cn.ym.mall.dao.impl;

import cn.ym.mall.dao.TypeDao;
import cn.ym.mall.entity.Brand;
import cn.ym.mall.entity.Type;
import cn.ym.mall.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 漆家乐
 * 类别实现类
 */
public class TypeDaoImpl implements TypeDao {
    QueryRunner queryRunner = new QueryRunner();
    /**
     * 查询所有类型
     *
     * @return
     */
    @Override
    public List<Type> getAll() throws SQLException {
        List<Type> typesList = new ArrayList<Type>();
        try{
            String sql = "select * from brand;";
            typesList = queryRunner.query(DruidUtils.getConnection(),sql,new BeanListHandler<Type>(Type.class));
        }catch (Exception e){
            e.printStackTrace();
        }
        return typesList;
    }

    /**
     * 根据id查询类型
     *
     * @param tid
     * @return
     */
    @Override
    public Type getTypeByTid(Integer tid) throws SQLException {
        Type type = null;
        try{
            String sql = "select * from type where tid = '?';";
            type = queryRunner.query(sql,new BeanHandler<Type>(Type.class),tid);
        }catch (Exception e){
            e.printStackTrace();
        }
        return type;
    }

    /**
     * 新增类型
     *
     * @param type
     * @return
     */
    @Override
    public int add(Type type) throws SQLException {
        int num = 0;
        try{
            String sql = "insert into brand(tid,tname) value(?,?);";
            num = queryRunner.update(DruidUtils.getConnection(),sql,type);
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }

    /**
     * 修改类型
     *
     * @param type
     * @return
     */
    @Override
    public int update(Type type) throws SQLException {
        int num = 0;
        try{
            String sql = "update brand set tname=? where tid=?;";
            num = queryRunner.update(DruidUtils.getConnection(),sql,type);
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }

    /**
     * 删除类型
     *
     * @param tid
     * @return
     */
    @Override
    public int delete(Integer tid) throws SQLException {
        int num = 0;
        try{
            String sql = "delete from brand where tid='?';";
            num = queryRunner.update(DruidUtils.getConnection(),sql,tid);
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }
}
